<!-- 角色管理 -->

<template>
  <div class="container">
    <div class="app-container" v-loading="isLoading">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="small" type="primary" @click="showDialog = true">新增角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template slot-scope="{ row }">
            <!-- 编辑状态 -->
            <el-input v-if="row.isEdit" v-model.trim="row.editRow.name" size="mini"></el-input>
            <!-- 未编辑状态 -->
            <span v-else> {{ row.name }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template slot-scope="{ row }">
            <!-- 编辑状态 -->
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0"></el-switch>
            <!-- 未编辑状态 -->
            <span v-else> {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template slot-scope="{ row }">
            <!-- 编辑状态 -->
            <el-input v-if="row.isEdit" v-model.trim="row.editRow.description" type="textarea" size="mini"></el-input>
            <!-- 未编辑状态 -->
            <span v-else> {{ row.description }} </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <template v-if="row.isEdit">
              <!-- 编辑状态 -->
              <el-button type="primary" size="mini" @click="editRole(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="editRoleBtn(row)">编辑</el-button>
              <el-popconfirm title="确定删除此角色嘛？" @onConfirm="delRole(row.id)">
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 分页 -->
        <el-pagination :page-size="pageParams.pagesize" :current-page="pageParams.page" :total="pageParams.total"
          layout="prev, pager, next" @current-change="changePage"></el-pagination>
      </el-row>
    </div>
    <!-- 新增角色 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="reset">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="addRole">确定</el-button>
              <el-button size="mini" @click="reset">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree ref="permTree" check-strictly node-key="id" :data="permissionData" :props="{ label: 'name' }" show-checkbox
        default-expand-all :default-checked-keys="permIds" />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleListAPI, addRoleAPI, editRoleAPI, delRoleAPI, getRoleDetailAPI, assignPermAPI } from "@/api/role.js"
import { getPermissionAPI } from "@/api/permission.js"
import { listToTreeData } from "@/utils/index.js"

export default {
  name: 'Role',
  data() {
    return {
      isLoading: true,
      roleList: [],  // 表格数据
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页数据条数
        total: 0   // 数据总数
      },
      showDialog: false,  // 弹窗显示隐藏
      roleForm: { // 弹窗表单数据
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {  // 校验规则
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: [] // 角色列表
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表数据
    async getRoleList() {
      this.isLoading = true
      const { rows, total } = await getRoleListAPI(this.pageParams)
      this.roleList = rows
      this.pageParams.total = total
      this.roleList.forEach(item => { // 动态添加isEdit属性
        this.$set(item, "isEdit", false)
        this.$set(item, "editRow", {  // 添加 编辑表单数据
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.isLoading = false
    },
    // 切换分页 请求新数据
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    // 新增角色
    addRole() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRoleAPI(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.reset()
        }
      })
    },
    // 关闭弹窗
    reset() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 编辑角色
    editRoleBtn(row) {
      row.isEdit = true
      // 编辑表单更新最新数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 确定-修改角色
    async editRole(row) {
      if (row.editRow.name && row.editRow.description) {
        await editRoleAPI({ ...row.editRow, id: row.id })
        // 更新成功
        this.$message.success('更新角色成功')
        row.isEdit = false
        // 更新页面数据
        row.name = row.editRow.name
        row.state = row.editRow.state
        row.description = row.editRow.description
      } else {
        this.$message.warning("角色和描述不能为空")
      }
    },
    // 删除角色
    async delRole(id) {
      await delRoleAPI(id)
      this.$message.success("删除角色成功")
      if (this.roleList.length === 1) { // 是否当前页最后一个
        this.pageParams.page--  // 返回上一个页码
      }
      this.getRoleList()
    },
    // 分配权限按钮
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetailAPI(id)  // 获取角色列表
      this.permIds = permIds
      this.permissionData = listToTreeData(await getPermissionAPI(), 0) // 获取权限列表并转为树形结构
      this.showPermissionDialog = true
    },
    // 分配权限
    async btnPermissionOK() {
      await assignPermAPI({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>

<style scoped>
.role-operate {
  padding: 20px;
}
</style>